package com.cheyun.netsalev3.viewmodel

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Looper
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.appcompat.app.AlertDialog
import com.cheyun.netsalev3.PlatformSdk
import com.cheyun.netsalev3.bean.Version
import com.cheyun.netsalev3.bean.dm.DmLogin
import com.cheyun.netsalev3.repository.LoginRepository
import com.cheyun.netsalev3.tencenttim.utils.DemoLog
import com.cheyun.netsalev3.view.LoginActivity
import com.cheyun.netsalev3.view.MainActivity
import com.cheyun.netsalev3.utils.*
import com.cheyun.netsalev3.utils.api.ApiStores.Companion.DOWN_URL
import com.cheyun.netsalev3.utils.api.DmApiClient
import com.cheyun.netsalev3.utils.api.DmBaseResp
import com.cheyun.netsalev3.utils.api.dm.DmApiCallback
import com.cheyun.netsalev3.utils.api.dm.DmApiException
import com.cheyun.netsalev3.view.BindDistributorActivity
import com.cheyun.netsalev3.view.dm.DmMainActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.text.SimpleDateFormat
import java.util.*

class WelComeActivityViewModel : BaseViewModel() {
    var password: String = MySharedPreferences.getPassword()
    var mobile: String = MySharedPreferences.getMobile()
    private var loginRepository = LoginRepository()
    var login = MySharedPreferences.getLoginData()
    var dmCauthkey = MySharedPreferences.getDMCauthkey()
//    var guide = MySharedPreferences.getGuide()
    var currentVersion  = ""
    lateinit var context:Context
    var hasPermissions:Boolean = true
    var activity : Activity? = null

    var agreeYs = MySharedPreferences.getAgreeYs()
    var showYsWindow = MutableLiveData<Boolean>(false)
    var showRefuseYsWindow = MutableLiveData<Boolean>(false)

    init{
        val formatter = SimpleDateFormat("yyyyMMddHHmmssSSS")
        val time = formatter.format(Date())
        Log.i("WelComeActivity","time mode init :"+time)
    }


    fun initData() {
        if(!agreeYs){
            showYsWindow.postValue(true)
            return
        }
        startApp()
    }

    fun confirmAgreeYsCallback(){
        MySharedPreferences.setAgreeYs(true)
        startApp()
    }

    fun refuseYs(){
        showRefuseYsWindow.postValue(true)
    }
    fun startApp(){
        PlatformSdk.initPlatformSdk()
        if (login == null && dmCauthkey.isNullOrBlank()) {
            myStartActivity(MyIntent(LoginActivity::class.java))
            myFinish()
        } else {
            loginRepository.Login2(mobile, password, this::setData, this::loginFail,this::goDm)
        }
    }

    fun checkVersion(applicationContext:Context,mContext:Context){
        context = mContext
        currentVersion = FunctionUtils.getCurrentVersion(applicationContext)
        loginRepository.getVersion(currentVersion,"android", this::setVersion)
    }

    fun setVersion(data:Version){

        initData()

//        if(data.update == 0){
//            initData()
//        }else{
//            var url = DOWN_URL+ data.version+".apk"
//            Looper.prepare()
//            if(data.update == 2){
//                var dialog = AlertDialog.Builder(context)
//                        .setTitle("更新提示")
//                        .setMessage("有新的版本，请更新")
//                        .setPositiveButton("确定"){ dialog, which ->  openApk(url,data.version) }
//                        .show()
//                FunctionUtils.setAlertDialogPos(dialog)
//            }else{
//                var dialog = AlertDialog.Builder(context)
//                        .setTitle("更新提示")
//                        .setMessage("有新的版本，是否前往更新")
//                        .setPositiveButton("是"){ dialog, which ->  openApk(url,data.version) }
//                        .setNegativeButton("否") { dialog, which -> initData() }
//                        .show()
//                FunctionUtils.setAlertDialogPos(dialog)
//
//            }
//            Looper.loop()
//        }
    }

    fun openApk(url:String,version:String){
        hasPermissions = false;
        if(hasPermissions){
            DownloadUtils(context).showDownloadDialog(url,version,true)
        }else{
            var intent = Intent();
            intent.setData(Uri.parse(url))
            intent.setAction(Intent.ACTION_VIEW)
            context.startActivity(intent);
        }
    }

    /**
     * 登录回调
     */
    fun setData() {
        if(MySharedPreferences.getLoginData()?.member?.uid == 0){
            var intent = MyIntent(BindDistributorActivity::class.java)
            intent.putExtra("single",true)
            myStartActivity(intent)
            myFinish()
            MyToast("登录成功，请等待管理员审核通过")
            return
        }
//        //当前通道是否是2s店员工登录到4s店
//        if(MySharedPreferences.getLoginData()?.channel?.is2sdms == 1){
//            var intent = MyIntent(BindDistributorActivity::class.java)
//            intent.putExtra("single",true)
//            myStartActivity(intent)
//            myFinish()
////            MyToast("登录成功，请等待管理员审核通过")
//            return
//        }
        goCrm()
//        getKefuBusyInfo()

    }

    fun goCrm(){
        myStartActivity(MyIntent(MainActivity::class.java))
        myFinish()
    }


    fun loginFail() {
        myStartActivity(MyIntent(LoginActivity::class.java))
        myFinish()
    }

//    fun getKefuBusyInfo(){
//        DmApiClient.getInstance().kefuBusyInfo(mobile)
//                .subscribeOn(Schedulers.io())
//                .subscribeOn(AndroidSchedulers.mainThread())
//                .subscribe(object : DmApiCallback<DmBaseResp<Any, Any>>() {
//                    override fun onSuccess(t: DmBaseResp<Any, Any>) {
//                        if(t.list!!.equals("0")) {
//                            timLogin()
//                        }else{
//                            MyApplication.getInstance().setTimOffline(true)
//                        }
//                    }
//
//                    override fun onError(ex: DmApiException) {
//
//                    }
//                })
//    }

//    fun timLogin(){
//        val userSig = GenerateTestUserSig.genTestUserSig(mobile)
//        TUIKit.login(mobile, userSig, object : IUIKitCallBack {
//            override fun onError(module: String, code: Int, desc: String) {
//                DemoLog.i("tim login", "imLogin errorCode = $code, errorInfo = $desc")
//            }
//
//            override fun onSuccess(data: Any?) {
//                DemoLog.i("tim login", "imLogin success")
//
//                var unreadMessageNum = 0
//                var msgList = TIMManager.getInstance().conversationList
//                if(msgList.size>0){
//                    for (i in 0 until msgList.size){
//                        unreadMessageNum = unreadMessageNum + msgList[i].unreadMessageNum.toInt()
//                    }
//                }
//                LiveEventBus.get().with("chatNum").postValue(unreadMessageNum)
//                DmApiClient.getInstance().kefuBusy(mobile,"0")
//                        .subscribeOn(Schedulers.io())
//                        .subscribeOn(AndroidSchedulers.mainThread())
//                        .subscribe(object : DmApiCallback<DmBaseResp<Any, Any>>() {
//                            override fun onSuccess(t: DmBaseResp<Any, Any>) {
//                                MyApplication.getInstance().setTimOffline(false)
//                                MyApplication.getInstance().setTimBusying(false)
//                            }
//
//                            override fun onError(ex: DmApiException) {
//
//                            }
//                        })
////                ThirdRegIdMgr.prepareThirdPushToken(activity)
//                ThirdPushTokenMgr.getInstance().setPushTokenToTIM();
//            }
//        })
//    }

    fun goDm(key:String){
        var channel = MySharedPreferences.getChannel();
        DmApiClient.getInstance().login(mobile,CommonFunc.textToMD5L32(password), channel)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DmApiCallback<DmBaseResp<DmLogin, Any>>() {
                    override fun onSuccess(t: DmBaseResp<DmLogin, Any>) {
                        t.list.apply {
                            DemoLog.d("WelComeActivity","entry DmMainActivity")
                            MySharedPreferences.putDMCauthkey(this?.auth.toString())
                            MySharedPreferences.putDMMgr(this?.clue_mgr!!)
                            MySharedPreferences.putDmLoginData(this);
                            var intent = MyIntent(DmMainActivity::class.java)
                            intent.putExtra("showMy",true);
                            myStartActivity(intent)
                            myFinish()
                        }
                    }
                    override fun onError(ex: DmApiException) {
                        myStartActivity(MyIntent(LoginActivity::class.java))
                        myFinish()
                    }
                })
    }


}